/*
 * @Author: zdc 3215400595@qq.com
 * @Date: 2023-08-06 14:36:29
 * @LastEditors: zdc 3215400595@qq.com
 * @LastEditTime: 2023-08-08 17:05:25
 * @FilePath: /Logs_System/logger.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 日志器模块

#ifndef _M_LOGGER_H__
#define _M_LOGGER_H__

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include "util.hpp"
#include "level.hpp"
#include "sink.hpp"
#include "format.hpp"
#include "looper.hpp"
#include <atomic>
#include <vector>
#include <mutex>
#include <cstdarg>
#include <cstdlib>
#include <functional>
#include <unordered_map>
namespace tong_log
{
    class Logger
    {
    public:
        using ptr = std::shared_ptr<Logger>;

    public:
        Logger(const std::string &logger_name,
               Formatter::ptr &formatter,
               std::vector<LogSink::ptr> &sinks,
               LogLevel::value level = LogLevel::value::DEBUG) : _logger_name(logger_name),
                                                                 _limit_level(level),
                                                                 _formatter(formatter),
                                                                 _sinks(sinks.begin(), sinks.end()) {}

    public:
        // 通过传入的参数，构建出一个日志消息对象，进行日志的格式化，最终落地
        void debug(const std::string &file, size_t line, const std::string &fmt, ...)
        {
            // 1.判断当前的日志是都到达了日志输出等级
            if (LogLevel::value::DEBUG < _limit_level)
                return;

            // 2.对fmt格式化字符串和不定参进行字符串组织，得到日志消息的字符串
            va_list ap;
            va_start(ap, fmt);
            char *res;
            int ret = vasprintf(&res, fmt.c_str(), ap);
            if (ret == -1)
            {
                std::cerr << "vasprint failed!\n";
                return;
            }
            va_end(ap);
            serialize(LogLevel::value::DEBUG, file, line, res);
            free(res);
        }
        void info(const std::string &file, size_t line, const std::string &fmt, ...)
        {
            if (LogLevel::value::INFO < _limit_level)
                return;

            va_list ap;
            va_start(ap, fmt);
            char *res;
            int ret = vasprintf(&res, fmt.c_str(), ap);
            if (ret == -1)
            {
                std::cerr << "vasprint failed!\n";
                return;
            }
            va_end(ap);
            serialize(LogLevel::value::INFO, file, line, res);
            free(res);
        }
        void warn(const std::string &file, size_t line, const std::string &fmt, ...)
        {
            if (LogLevel::value::WARN < _limit_level)
                return;

            va_list ap;
            va_start(ap, fmt);
            char *res;
            int ret = vasprintf(&res, fmt.c_str(), ap);
            if (ret == -1)
            {
                std::cerr << "vasprint failed!\n";
                return;
            }
            va_end(ap);
            serialize(LogLevel::value::WARN, file, line, res);
            free(res);
        }
        void error(const std::string &file, size_t line, const std::string &fmt, ...)
        {
            if (LogLevel::value::ERROR < _limit_level)
                return;

            va_list ap;
            va_start(ap, fmt);
            char *res;
            int ret = vasprintf(&res, fmt.c_str(), ap);
            if (ret == -1)
            {
                std::cerr << "vasprint failed!\n";
                return;
            }
            va_end(ap);
            serialize(LogLevel::value::ERROR, file, line, res);
            free(res);
        }
        void fatal(const std::string &file, size_t line, const std::string &fmt, ...)
        {
            if (LogLevel::value::FATAL < _limit_level)
                return;

            va_list ap;
            va_start(ap, fmt);
            char *res;
            int ret = vasprintf(&res, fmt.c_str(), ap);
            if (ret == -1)
            {
                std::cerr << "vasprint failed!\n";
                return;
            }
            va_end(ap);
            serialize(LogLevel::value::FATAL, file, line, res);
            free(res);
        }

    public:
        const std::string &name()
        {
            return _logger_name;
        }

    protected:
        // 将日志消息序列化
        void serialize(LogLevel::value level, const std::string &file, size_t line, char *str)
        {
            // 3.构造LogMsg对象
            LogMsg msg(level, line, file, _logger_name, str);
            // 4.通过格式化工具，对logMsg进行格式化，得到格式化后的日志字符串
            std::stringstream ss;
            _formatter->format(ss, msg);
            // 5.进行日志落地
            log(ss.str().c_str(), ss.str().size());
        }
        // 抽象接口完成落地输出，不同的日志日志器，会有不同的实际落地方式
        virtual void log(const char *data, size_t len) = 0;

    protected:
        std::mutex _mutex;
        std::string _logger_name;
        std::atomic<LogLevel::value> _limit_level;
        Formatter::ptr _formatter;
        std::vector<LogSink::ptr> _sinks;
    };

    // 同步日志器类
    class SyncLogger : public Logger
    {
    public:
        SyncLogger(const std::string &logger_name,
                   Formatter::ptr &formatter,
                   std::vector<LogSink::ptr> &sinks,
                   LogLevel::value level = LogLevel::value::DEBUG)
            : Logger(logger_name, formatter, sinks, level) {}

    protected:
        void log(const char *data, size_t len)
        {
            // 加锁
            std::unique_lock<std::mutex> lock(_mutex);
            if (_sinks.empty())
                return;
            for (auto &sink : _sinks)
            {
                sink->log(data, len);
            }
        }
    };

    // 异步日志器
    class AsyncLogger : public Logger
    {
    public:
        AsyncLogger(const std::string &logger_name,
                    Formatter::ptr &formatter,
                    std::vector<LogSink::ptr> &sinks,
                    LogLevel::value level,
                    AsyncType looper_type)
            : Logger(logger_name, formatter, sinks, level),
              _looper(std::make_shared<AsyncLooper>(std::bind(&AsyncLogger::realLog, this, std::placeholders::_1), looper_type)) {}

    protected:
        void log(const char *data, size_t len) // 将日志写入缓冲区
        {
            _looper->push(data, len);
        }
        // 实际落地函数
        void realLog(Buffer &buf)
        {
            if (_sinks.empty())
                return;
            for (auto &sink : _sinks)
            {
                sink->log(buf.begin(), buf.readAbleSize());
            }
        }

    private:
        AsyncLooper::ptr _looper;
    };
    enum class LoggerType
    {
        LOGGER_SYNC,
        LOGGER_ASYNC
    };
    // 使用建造者模式建造日志器，而不要让用户直接构建日志器，简化用户的复杂度
    class LoggerBuilder
    {
    public:
        LoggerBuilder() : _logger_type(LoggerType::LOGGER_SYNC),
                          _limit_level(LogLevel::value::DEBUG),
                          _looper_type(AsyncType::ASYNC_SAFE) {}

    public:
        void buildLoggerType(LoggerType type) { _logger_type = type; }
        void buildLoggerName(const std::string &name) { _logger_name = name; }
        void buildLoggerLevel(LogLevel::value level) { _limit_level = level; }
        void buildEnableUnsafeAsync() { _looper_type = AsyncType::ASYNC_UNSAFE; }
        void buildLoggerFormatter(const std::string &pattern)
        {
            _formatter = std::make_shared<Formatter>(pattern);
        }
        template <class SinkType, class... Args>
        void buildSink(Args &&...args)
        {
            LogSink::ptr psick = SinkFactory::create<SinkType>(std::forward<Args>(args)...);
            _sinks.push_back(psick);
        }

    public: // 建造日志器
        virtual Logger::ptr build() = 0;

    protected:
        LoggerType _logger_type;
        std::string _logger_name; // 必须要去bulid，标识日志器
        LogLevel::value _limit_level;
        Formatter::ptr _formatter;
        std::vector<LogSink::ptr> _sinks;
        AsyncType _looper_type;
    };

    // 局部建造者
    class LocalLoggerBulider : public LoggerBuilder
    {
    public:
        Logger::ptr build() override
        {
            assert(_logger_name.empty() == false); // 必须有日志器的名称
            if (_formatter.get() == nullptr)       // 如果没有格式化类型，设置一个默认的
            {
                _formatter = std::make_shared<Formatter>();
            }
            if (_sinks.empty()) // 落地器数组为空，默认设置一个标准输出的落地器
            {
                buildSink<StdoutSink>();
            }

            // 限制各个零件就都有了
            if (_logger_type == LoggerType::LOGGER_ASYNC) // 异步日志器
            {
                return std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _limit_level, _looper_type);
            }
            else // 同步日志器
            {
                return std::make_shared<SyncLogger>(_logger_name, _formatter, _sinks, _limit_level);
            }
        }
    };

    // 日志管理器
    class LoggerManager
    {
    public:
        void addLogger(Logger::ptr &logger)
        {
            if (hasLogger(logger->name()))
                return;
            std::unique_lock<std::mutex> _lock(_mutex);
            _loggers.insert(std::make_pair(logger->name(), logger));
        }
        bool hasLogger(const std::string &name)
        {
            auto it = _loggers.find(name);
            if (it == _loggers.end())
                return false;
            return true;
        }
        Logger::ptr getLogger(const std::string &name)
        {
            auto it = _loggers.find(name);
            if (it == _loggers.end())
                return Logger::ptr();
            return it->second;
        }
        Logger::ptr rootLogger()
        {
            return _root_logger;
        }

    public:
        static LoggerManager &getInstance() // 使用懒汉模式，获取单例对象
        {
            static LoggerManager eton;
            return eton;
        }

    private:
        LoggerManager()
        {
            std::unique_ptr<tong_log::LoggerBuilder> builder(new tong_log::LocalLoggerBulider());
            builder->buildLoggerName("root");
            _root_logger = builder->build();
            _loggers.insert(make_pair(_root_logger->name(),_root_logger));
        }

    private:
        std::mutex _mutex;
        Logger::ptr _root_logger; // 默认日志器
        std::unordered_map<std::string, Logger::ptr> _loggers;
    };

    //全局日志器建造者
     class GlobalLoggerBulider : public LoggerBuilder
    {
    public:
        Logger::ptr build() override
        {
            assert(_logger_name.empty() == false); // 必须有日志器的名称
            if (_formatter.get() == nullptr)       // 如果没有格式化类型，设置一个默认的
            {
                _formatter = std::make_shared<Formatter>();
            }
            if (_sinks.empty()) // 落地器数组为空，默认设置一个标准输出的落地器
            {
                buildSink<StdoutSink>();
            }
            Logger::ptr logger;
            // 限制各个零件就都有了
            if (_logger_type == LoggerType::LOGGER_ASYNC) // 异步日志器
            {
                logger = std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _limit_level, _looper_type);
            }
            else // 同步日志器
            {
                logger =  std::make_shared<SyncLogger>(_logger_name, _formatter, _sinks, _limit_level);
            }
            LoggerManager::getInstance().addLogger(logger);
            return logger;
        }
    };
}
#endif